﻿using DemormTest.Common.ExtensionUtil;
using rmTest.Common.AttrUtil;
using rmTest.Common.CacheUtil;
using rmTest.Common.ExtensionUtil;
using rmTest.Common.ModelUtil;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace rmTest.Common.DataBaseUtil
{
    public static class ExpressionHelper
    {
        #region
        /// <summary>
        /// DataTable生成实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dataTable) where T : BaseModel, new()
        {
            if (dataTable == null || dataTable.Rows.Count <= 0) throw new ArgumentNullException("dataTable", "当前对象为null无法生成表达式树");
            Func<DataRow, T> func = dataTable.Rows[0].ToExpression<T>();
            List<T> collection = new List<T>(dataTable.Rows.Count);
            foreach (DataRow dr in dataTable.Rows)
            {
                collection.Add(func(dr));
            }
            return collection;
        }

        /// <summary>
        /// 生成表达式，没有解决可为空类型问题
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataRow"></param>
        /// <returns></returns>
        public static Func<DataRow, T> ToExpression<T>(this DataRow dataRow) where T : BaseModel, new()
        {
            if (FuncCache<DataRow, T>._FUNC != null)
            {
                return FuncCache<DataRow, T>._FUNC;
            }
            else
            {

                if (dataRow == null) throw new ArgumentNullException("dataRow", "当前对象为null 无法转换成实体");
                ParameterExpression parameter = Expression.Parameter(typeof(DataRow), "dr");
                List<MemberBinding> binds = new List<MemberBinding>();
                for (int i = 0; i < dataRow.ItemArray.Length; i++)
                {
                    String colName = dataRow.Table.Columns[i].ColumnName;
                    PropertyInfo pInfo = typeof(T).GetProperty(colName);
                    if (pInfo == null || !pInfo.CanWrite) continue;
                    MethodInfo mInfo = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(String) }).MakeGenericMethod(pInfo.PropertyType);
                    MethodCallExpression call = Expression.Call(mInfo, parameter, Expression.Constant(colName, typeof(String)));
                    MemberAssignment bind = Expression.Bind(pInfo, call);
                    binds.Add(bind);
                }
                MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(T)), binds.ToArray());
                FuncCache<DataRow, T>._FUNC = Expression.Lambda<Func<DataRow, T>>(init, parameter).Compile();
            }
            return FuncCache<DataRow, T>._FUNC;
        }
        #endregion

        /// <summary>
        /// 生成表达式目录树，并使用缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static Func<SqlDataReader, T> ToExpression<T>(this SqlDataReader reader) where T : BaseModel, new()//: class, new()
        {
            if (FuncCache<SqlDataReader, T>._FUNC != null)
            {
                return FuncCache<SqlDataReader, T>._FUNC;
            }
            else
            {
                //定义一个参数 参数名r
                ParameterExpression parameterExpression = Expression.Parameter(typeof(SqlDataReader), "r");
                //定义一个对类型SqlDataReader 中 get_Item方法的调用 
                MethodInfo methodInfoGet = typeof(SqlDataReader).GetMethod("get_Item", new Type[] { typeof(string) });
                //定义一个对类型ObjectExtensions 中 ConvertToTheType 方法的调用，为了实现 属性的类型转换后的值 
                MethodInfo methodInfoConvert = typeof(ObjectExtensions).GetMethod("ConvertToTheType", new Type[] { typeof(Object) });

                List<MemberBinding> memberBindings = new List<MemberBinding>();

                foreach (var property in typeof(T).GetProperties())
                {
                    if (property == null || !property.CanWrite) continue;
                    //获取属性对应的数据表字段
                    string name = property.GetMemberInfoDisplayValue();
                    ModelBaseValidateAttribute modelAttr = property.GetCustomAttribute<ModelBaseValidateAttribute>();//获取属性的指定特性
                    if (modelAttr == null || !modelAttr.Ignored)//无特性值为空或者表示不是数据表忽略字段时
                    {
                        // 定义一个常量表达式，值为 数据表属性名
                        ConstantExpression constant = Expression.Constant(name);
                        //调用方法 get_Item
                        //调用 reader 参数 r 对 字段 的方法 get_Item，获取reader中参数值
                        MethodCallExpression callValue = Expression.Call(parameterExpression, methodInfoGet, constant);
                        //获取泛型方法ConvertToTheType，传入属性类型，并调用方法返回结果，为了实现 获取属性的类型转换 的值
                        MethodInfo makeGenericMethod = methodInfoConvert.MakeGenericMethod(new Type[] { property.PropertyType });
                        //传入 reader值callValue，并调用赋值方法
                        MethodCallExpression call = Expression.Call(null, makeGenericMethod, new Expression[] { callValue });
                        //把属性进行初始化赋值
                        MemberAssignment bing = Expression.Bind(property, call);
                        memberBindings.Add(bing);
                    }
                }
                //构建一个T实例并进行属性绑定
                MemberInitExpression memberInit = Expression.MemberInit(Expression.New(typeof(T)), memberBindings.ToArray());
                Expression<Func<SqlDataReader, T>> expression = Expression.Lambda<Func<SqlDataReader, T>>
                (
                    memberInit,
                    new ParameterExpression[] { parameterExpression }
                );
                FuncCache<SqlDataReader, T>._FUNC = expression.Compile();
            }
            return FuncCache<SqlDataReader, T>._FUNC;
        }
    }
}
